﻿using hyjx.comm.Exceptions;
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;

namespace hyjx.comm
{
    /// <summary>
    /// 红运 TCP 服务
    /// </summary>
    public class HyTcpServer : TcpSharp.TcpSharpSocketServer
    {
        /// <summary>
        /// 创建一个新的红运 TCP 服务
        /// </summary>
        /// <param name="port">端口</param>
        public HyTcpServer(int port) : base(port)
        { 
        }

        /// <summary>
        /// 检查客户端是否连接
        /// </summary>
        /// <param name="connectionId">连接编号</param>
        /// <exception cref="CheckClientIsConnectedException">检查客户端是否连接出现错误</exception>
        /// <returns></returns>
        public bool CheckClientIsConnected(string connectionId)
        {
            try
            {
                var client = this.GetClient(connectionId);
                bool pollResult = client.Client.Client.Poll(1000, System.Net.Sockets.SelectMode.SelectRead);
                if (!pollResult)
                    return true;

                if (client.Client.Available == 0)
                    return false;

                return true;
            }
            catch(ArgumentNullException ex)
            {
                throw new CheckClientIsConnectedException(nameof(ArgumentNullException), ex);
            }
            catch(NotSupportedException ex)
            {
                throw new CheckClientIsConnectedException(nameof(NotSupportedException), ex);
            }
            catch(SocketException ex)
            {
                throw new CheckClientIsConnectedException(nameof(SocketException), ex);
            }
            catch(ObjectDisposedException ex)
            {
                throw new CheckClientIsConnectedException(nameof(ObjectDisposedException), ex);
            }
            catch(Exception ex)
            {
                throw new CheckClientIsConnectedException(nameof(Exception), ex);
            }
        }
    }
}
